<template>
  <div>
    <div class="margin-bottom">
      <el-input
        clearable
        placeholder="输入用户名称搜索"
        size="mini"
        style="width: 200px;"
        class="filter-item"
      />
      <el-button class="filter-item" size="mini" type="success" icon="el-icon-search">搜索</el-button>
      <div style="float:right">
        <el-button
          class="filter-item"
          size="mini"
          type="primary"
          icon="el-icon-plus"
          @click="add"
        >新增</el-button>
      </div>
    </div>
    <el-table v-loading="loading" :data="operatorList" style="width: 100%" border>
      <el-table-column prop="loginName" label="昵称"/>
      <el-table-column prop="realName" label="姓名"/>
      <el-table-column prop="mobile" label="手机号"/>
      <!-- <el-table-column prop="company" label="所属公司"/>
      <el-table-column prop="position" label="所在职位"/>-->
      <el-table-column label="操作" align="center">
        <template slot-scope="scope">
          <!-- <el-button type="primary" size="mini" icon="el-icon-key" @click="pwdReset(scope.row)"/> -->
          <el-button type="primary" size="mini" icon="el-icon-edit" @click="handleEdit(scope.row)"/>
          <el-popover :ref="scope.row.uuid" placement="top" width="180">
            <p>确定锁定该管理员吗？</p>
            <div style="text-align: right; margin: 0">
              <el-button size="mini" type="text" @click="$refs[scope.row.uuid].doClose()">取消</el-button>
              <el-button
                :loading="delLoading"
                type="primary"
                size="mini"
                @click="lock(scope.row.uuid)"
              >确定</el-button>
            </div>
            <el-button slot="reference" type="warning" size="mini" icon="el-icon-lock"/>
          </el-popover>
        </template>
      </el-table-column>
    </el-table>
    <el-pagination
      class="margin-top"
      background
      layout="prev, pager, next"
      :page-count="pageConfig.total"
      @current-change="currentChange"
    />
    <el-dialog :close-on-click-modal="false" title="重置密码" :visible.sync="pwdShow" width="600px">
      <el-form ref="form" :model="pwdForm" :rules="rules" label-width="100px">
        <el-form-item label="旧密码" prop="oldPassword">
          <el-input v-model="pwdForm.oldPassword" auto-complete="off" class="el-input-width"/>
        </el-form-item>
        <el-form-item label="新密码" prop="newPassword">
          <el-input v-model="pwdForm.newPassword" auto-complete="off" class="el-input-width"/>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="pwdShow = false">取 消</el-button>
        <el-button type="primary" :loading="pwdLoading" @click="reset()">确 定</el-button>
      </div>
    </el-dialog>
    <el-dialog
      :close-on-click-modal="false"
      :title="!isEdit?'新建操作员':'编辑操作员'"
      :visible.sync="isShow"
      width="600px"
    >
      <el-form
        ref="form"
        v-loading="dialogLoading"
        :model="form"
        :rules="rules"
        label-width="100px"
      >
        <el-form-item label="姓名" prop="realName">
          <el-input v-model="form.realName" auto-complete="off" class="el-input-width"/>
        </el-form-item>
        <el-form-item label="登录名" prop="loginName">
          <el-input v-model="form.loginName" auto-complete="off" class="el-input-width"/>
        </el-form-item>
        <el-form-item label="手机号" prop="mobile">
          <el-input
            v-model="form.mobile"
            maxlength="11"
            minlength="11"
            auto-complete="off"
            class="el-input-width"
          />
        </el-form-item>
        <el-form-item v-if="!isEdit" label="登录密码" prop="loginPassword">
          <el-input
            v-model="form.loginPassword"
            auto-complete="off"
            type="password"
            class="el-input-width"
            show-password
          />
        </el-form-item>
        <el-form-item v-if="!isEdit" label="确认密码" prop="loginPasswordConfirm">
          <el-input
            v-model="form.loginPasswordConfirm"
            auto-complete="off"
            type="password"
            class="el-input-width"
            show-password
          />
        </el-form-item>
        <!-- <el-form-item label="选择公司" prop="company">
          <el-select v-model="form.company" filterable placeholder="请选择公司" class="el-input-width">
            <el-option
              v-for="item in companyList"
              :key="item.uuid"
              :label="item.name"
              :value="item.uuid"
            />
          </el-select>
        </el-form-item> -->
        <el-form-item label="选择角色" prop="roles">
          <el-select
            v-model="form.roles"
            multiple
            filterable
            placeholder="请选择角色"
            class="el-input-width"
          >
            <el-option
              v-for="item in roleList"
              :key="item.uuid"
              :label="item.roleName"
              :value="item.uuid"
            />
          </el-select>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="isShow = false">取 消</el-button>
        <el-button type="primary" :loading="isLoad" @click="confirm()">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>
<script>
import * as systemApi from '@/api/system';
export default {
  data() {
    const validatePass = (rule, value, callback) => {
      if (value === '') {
        callback(new Error('请输入密码确认'));
      } else if (this.form.loginPassword === this.form.loginPasswordConfirm) {
        callback();
      } else {
        callback(new Error('密码确认和密码不一致'));
      }
    };
    const passwordRule = (rule, value, callback) => {
      const pattern = /^[^\u4e00-\u9fa5]{6,}$/;
      if (!pattern.test(value)) {
        callback(new Error('至少输入6位以上非汉字字符'));
      } else {
        callback();
      }
    };
    return {
      operatorList: [],
      pwdShow: false,
      pwdLoading: false,
      loading: false,
      delLoading: false,
      dialogLoading: false,
      pageConfig: {
        page: 0,
        pageSize: 0,
        total: 0
      },
      roleList: [],
      companyList: [],
      isShow: false,
      isEdit: false,
      isLoad: false,
      pwdForm: {
        oldPassword: '',
        newPassword: ''
      },
      form: {
        loginName: '',
        loginPassword: '',
        realName: '',
        mobile: '',
        loginPasswordConfirm: ''
      },
      rules: {
        loginName: [
          { required: true, message: '请输入登录ID', trigger: 'blur' },
          { min: 3, max: 12, message: '长度在 3 到 12 个字符', trigger: 'blur' }
        ],
        loginPassword: [
          { required: true, message: '请输入登录密码', trigger: 'blur' },
          { validator: passwordRule }
        ],
        realName: [
          { required: true, message: '请输入您的姓名', trigger: 'blur' },
          { min: 2, max: 12, message: '长度在 2 到 12 个字符', trigger: 'blur' }
        ],
        mobile: [
          { required: true, message: '请输入您的手机号', trigger: 'blur' },
          { min: 11, max: 11, message: '长度在 11 个字符', trigger: 'blur' }
        ],
        roles: [{ required: true, message: '请选择角色', trigger: 'change' }],
        company: [{ required: true, message: '请选择公司', trigger: 'change' }],
        loginPasswordConfirm: [{ required: true, validator: validatePass }]
      }
    };
  },
  mounted() {
    this.getOperators();
    this.getRoles();
    this.getCompanies();
  },
  methods: {
    // 翻页相关
    currentChange(page) {
      this.pageConfig.page = page - 1;
      this.getOperators();
    },

    async getOperators() {
      this.loading = true;
      const params = {
        page: this.pageConfig.page,
        pageSize: 20
      };
      try {
        const res = await systemApi.operator_page(params);
        this.loading = false;
        const operatorList = res.data.pageData;
        this.operatorList = operatorList;
        this.pageConfig.total = res.data.total;
      } catch (error) {
        this.loading = false;
      }
    },
    async getRoles() {
      const res = await systemApi.role_all();
      this.roleList = res.data;
    },
    async getCompanies() {
      const res = await systemApi.company_all();
      this.companyList = res.data;
    },
    async getRolesById(id) {
      const res = await systemApi.operator_roles(id, { uuid: id });
      return res.data.reduce((init, cur) => {
        if (cur.role && cur.roleName) {
          init.push(cur.uuid);
        }
        return init;
      }, []);
    },
    async getCompanyById(id) {
      const res = await systemApi.operator_company(id);
      return res.data.uuid;
    },
    resetForm() {
      // this.$refs['form'].resetFields();
      this.form = {
        loginName: '',
        loginPassword: '',
        realName: '',
        mobile: '',
        loginPasswordConfirm: ''
      };
      this.isShow = false;
    },
    add() {
      this.isEdit = false;
      this.resetForm();
      this.isShow = true;
    },
    async handleEdit(operator) {
      this.isEdit = true;
      this.isShow = true;
      this.dialogLoading = true;
      this.form = JSON.parse(JSON.stringify(operator));
      const roles = await this.getRolesById(operator.uuid);
      // const company = (await this.getCompanyById(operator.uuid)) || '';
      this.$set(this.form, 'roles', roles);
      // this.$set(this.form, 'company', company);
      this.dialogLoading = false;
    },
    pwdReset(item) {
      this.pwdShow = true;
      this.pwdForm = {
        oldPassword: '',
        newPassword: ''
      };
    },
    async lock(uuid) {
      this.delLoading = true;
      await systemApi.operator_lock(uuid);
      this.$refs[uuid].doClose();
      this.$message({
        message: '已锁定',
        type: 'success'
      });
      this.delLoading = false;
      this.getOperators();
    },
    async createOperator(form) {
      try {
        const { roles, company, ...data } = form;
        const res = await systemApi.operator_add(data);
        const uuid = res.data;
        if (company) {
          await systemApi.operator_bind_companies({
            companyUuid: company,
            operatorUuid: uuid
          });
        }
        if (roles) {
          await systemApi.operator_bind_roles({
            operatorUuid: uuid,
            roleUuids: roles
          });
        }
        this.$message({
          message: '添加成功',
          type: 'success'
        });
        this.getOperators();
        this.resetForm();
        this.isLoad = false;
      } catch (error) {
        this.isLoad = false;
        console.error(error);
      }
    },
    async editOperator(form) {
      try {
        const { roles, company, ...data } = form;
        if (company) {
          await systemApi.operator_bind_companies({
            companyUuid: company,
            operatorUuid: data.uuid
          });
        }
        if (roles) {
          await systemApi.operator_bind_roles({
            operatorUuid: data.uuid,
            roleUuids: roles
          });
        }
        await systemApi.operator_update(data);
        this.$message({
          message: '修改成功',
          type: 'success'
        });
        this.resetForm();
        this.isLoad = false;
      } catch (error) {
        console.log(error);
        this.isLoad = false;
      }
    },
    confirm() {
      this.$refs['form'].validate(async valid => {
        if (valid) {
          this.isLoad = true;
          if (this.isEdit) {
            this.editOperator(this.form);
          } else {
            this.createOperator(this.form);
          }
        }
      });
    }
  }
};
</script>
